<template>
  <div class="policy-notification-center">
    <!-- 浮动通知弹窗 -->
    <transition-group name="notification-slide" tag="div" class="fixed top-20 right-6 z-50 space-y-3">
      <div
        v-for="notification in visibleNotifications"
        :key="notification.id"
        :class="[
          'notification-card max-w-sm rounded-xl p-4 shadow-2xl border transition-all duration-500',
          getNotificationStyle(notification.urgency),
          notification.isExpanded ? 'max-w-md' : ''
        ]"
        @click="expandNotification(notification)"
        @mouseenter="pauseAutoClose(notification)"
        @mouseleave="resumeAutoClose(notification)"
      >
        <!-- 通知头部 -->
        <div class="flex items-start justify-between mb-2">
          <div class="flex items-center space-x-2">
            <component 
              :is="getNotificationIcon(notification.type)" 
              :class="getIconColor(notification.urgency)"
              class="w-5 h-5 flex-shrink-0"
            />
            <h4 class="text-white font-semibold text-sm">{{ ts(notification.title) }}</h4>
          </div>
          <div class="flex items-center space-x-1">
            <div 
              :class="[
                'w-2 h-2 rounded-full',
                notification.urgency === 'high' ? 'bg-red-400 animate-pulse' : 
                notification.urgency === 'medium' ? 'bg-yellow-400' : 'bg-green-400'
              ]"
            ></div>
            <button
              @click.stop="dismissNotification(notification.id)"
              class="text-white/50 hover:text-white transition-colors"
            >
              <X class="w-4 h-4" />
            </button>
          </div>
        </div>

        <!-- 通知内容 -->
        <div class="mb-3">
          <p class="text-white/90 text-sm mb-2">{{ ts(notification.content) }}</p>
          
          <!-- 展开内容 -->
          <div v-if="notification.isExpanded && notification.data" class="space-y-2">
            <!-- 政策详情 -->
            <div v-if="notification.type === 'policy_update'" class="bg-white/10 rounded-lg p-3">
              <div class="text-xs text-electric-500 mb-1">政策影响评估</div>
              <div class="text-white/80 text-xs">
                影响程度: {{ notification.data.impact || '中等' }}
              </div>
              <div class="text-white/80 text-xs">
                生效时间: {{ formatDate(notification.data.effectDate) }}
              </div>
            </div>
            
            <!-- 推荐政策列表 -->
            <div v-if="notification.type === 'daily_digest' && notification.data" class="space-y-2">
              <div 
                v-for="policy in notification.data.slice(0, 3)" 
                :key="policy.id"
                class="bg-white/10 rounded-lg p-2"
              >
                <div class="text-white text-xs font-medium mb-1">{{ policy.title }}</div>
                <div class="text-electric-500 text-xs">{{ policy.benefit }}</div>
                <div class="flex items-center justify-between mt-1">
                  <span class="text-xs text-white/60">匹配度: {{ Math.round(policy.matchScore * 100) }}%</span>
                  <span 
                    :class="[
                      'text-xs px-2 py-1 rounded',
                      policy.urgency === 'high' ? 'bg-red-500/20 text-red-400' : 'bg-yellow-500/20 text-yellow-400'
                    ]"
                  >
                    {{ policy.urgency === 'high' ? '紧急' : '一般' }}
                  </span>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- 操作按钮 -->
        <div class="flex items-center justify-between">
          <span class="text-xs text-white/50">{{ formatTime(notification.timestamp) }}</span>
          <div class="flex items-center space-x-2">
            <button
              v-if="notification.type === 'policy_update'"
              @click.stop="viewPolicyDetails(notification)"
              class="text-xs px-3 py-1 bg-electric-500/20 text-electric-500 rounded hover:bg-electric-500/30 transition-colors"
            >
              查看详情
            </button>
            <button
              v-if="!notification.isExpanded"
              @click.stop="expandNotification(notification)"
              class="text-xs px-3 py-1 bg-white/10 text-white rounded hover:bg-white/20 transition-colors"
            >
              展开
            </button>
          </div>
        </div>

        <!-- 进度条 -->
        <div class="mt-2 w-full bg-white/10 rounded-full h-1">
          <div 
            class="bg-electric-500 h-1 rounded-full transition-all duration-100"
            :style="{ width: `${notification.progress}%` }"
          ></div>
        </div>
      </div>
    </transition-group>

    <!-- 通知历史抽屉 -->
    <div 
      v-if="showHistory"
      class="fixed inset-0 bg-black/50 z-60"
      @click="showHistory = false"
    >
      <div 
        class="fixed right-0 top-0 h-full w-96 bg-gray-900 border-l border-electric-500/30 transform transition-transform duration-300"
        @click.stop
      >
        <div class="flex items-center justify-between p-4 border-b border-electric-500/30">
          <h3 class="text-lg font-semibold text-white">通知历史</h3>
          <button @click="showHistory = false" class="text-white/70 hover:text-white">
            <X class="w-5 h-5" />
          </button>
        </div>
        
        <div class="overflow-y-auto h-full pb-20">
          <div class="p-4 space-y-3">
            <div 
              v-for="notification in notificationHistory" 
              :key="notification.id"
              class="bg-white/5 rounded-lg p-3 border border-white/10"
            >
              <div class="flex items-center justify-between mb-2">
                <div class="flex items-center space-x-2">
                  <component 
                    :is="getNotificationIcon(notification.type)" 
                    class="w-4 h-4 text-electric-500"
                  />
                  <span class="text-white text-sm font-medium">{{ ts(notification.title) }}</span>
                </div>
                <span class="text-xs text-white/50">{{ formatTime(notification.timestamp) }}</span>
              </div>
              <p class="text-white/70 text-xs">{{ ts(notification.content) }}</p>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 通知设置模态框 -->
    <div 
      v-if="showSettings"
      class="fixed inset-0 bg-black/50 z-60 flex items-center justify-center p-4"
      @click="showSettings = false"
    >
      <div 
        class="bg-gray-900 rounded-xl p-6 w-full max-w-md border border-electric-500/30"
        @click.stop
      >
        <div class="flex items-center justify-between mb-4">
          <h3 class="text-lg font-semibold text-white">通知设置</h3>
          <button @click="showSettings = false" class="text-white/70 hover:text-white">
            <X class="w-5 h-5" />
          </button>
        </div>
        
        <div class="space-y-4">
          <!-- 推送频率 -->
          <div>
            <label class="block text-sm font-medium text-white mb-2">推送频率</label>
            <select 
              v-model="settings.frequency"
              class="w-full bg-white/10 border border-white/20 rounded-lg px-3 py-2 text-white"
            >
              <option value="realtime">实时推送</option>
              <option value="hourly">每小时汇总</option>
              <option value="daily">每日摘要</option>
              <option value="weekly">每周报告</option>
            </select>
          </div>
          
          <!-- 推送时间 -->
          <div class="grid grid-cols-2 gap-4">
            <div>
              <label class="block text-sm font-medium text-white mb-2">开始时间</label>
              <input 
                v-model="settings.timeRange.start"
                type="time"
                class="w-full bg-white/10 border border-white/20 rounded-lg px-3 py-2 text-white"
              />
            </div>
            <div>
              <label class="block text-sm font-medium text-white mb-2">结束时间</label>
              <input 
                v-model="settings.timeRange.end"
                type="time"
                class="w-full bg-white/10 border border-white/20 rounded-lg px-3 py-2 text-white"
              />
            </div>
          </div>
          
          <!-- 优先级过滤 -->
          <div>
            <label class="block text-sm font-medium text-white mb-2">最低优先级</label>
            <select 
              v-model="settings.minPriority"
              class="w-full bg-white/10 border border-white/20 rounded-lg px-3 py-2 text-white"
            >
              <option value="low">低优先级</option>
              <option value="medium">中优先级</option>
              <option value="high">高优先级</option>
            </select>
          </div>
          
          <!-- 保存按钮 -->
          <button
            @click="saveSettings"
            class="w-full bg-electric-500 text-white py-2 rounded-lg hover:bg-electric-600 transition-colors"
          >
            保存设置
          </button>
        </div>
      </div>
    </div>

    <!-- 右下角控制按钮 -->
    <div class="fixed bottom-6 right-6 z-40 flex flex-col space-y-2">
      <!-- 历史记录按钮 -->
      <button
        @click="showHistory = true"
        class="w-12 h-12 bg-electric-500/20 backdrop-blur-sm text-electric-500 rounded-full hover:bg-electric-500/30 transition-all duration-300 flex items-center justify-center"
        title="查看通知历史"
      >
        <History class="w-5 h-5" />
      </button>
      
      <!-- 设置按钮 -->
      <button
        @click="showSettings = true"
        class="w-12 h-12 bg-tech-blue-500/20 backdrop-blur-sm text-tech-blue-400 rounded-full hover:bg-tech-blue-500/30 transition-all duration-300 flex items-center justify-center"
        title="通知设置"
      >
        <Settings class="w-5 h-5" />
      </button>
      
      <!-- 未读数量徽章 -->
      <div 
        v-if="unreadCount > 0"
        class="absolute -top-2 -right-2 w-6 h-6 bg-red-500 text-white text-xs rounded-full flex items-center justify-center font-bold animate-pulse"
      >
        {{ unreadCount > 99 ? '99+' : unreadCount }}
      </div>
    </div>
  </div>
</template>

<script>
import { 
  Bell, 
  AlertTriangle, 
  Info, 
  TrendingUp, 
  X, 
  History, 
  Settings,
  FileText,
  DollarSign,
  Building,
  Target
} from 'lucide-vue-next'
import { useTranslation } from '../composables/useTranslation.js'
import intelligentAgent from '../services/intelligentAgent.js'

export default {
  name: 'PolicyNotificationCenter',
  components: {
    Bell,
    AlertTriangle,
    Info,
    TrendingUp,
    X,
    History,
    Settings,
    FileText,
    DollarSign,
    Building,
    Target
  },
  setup() {
    const { ts } = useTranslation()
    return { ts }
  },
  data() {
    return {
      notifications: [],
      notificationHistory: [],
      visibleNotifications: [],
      showHistory: false,
      showSettings: false,
      autoCloseTimers: new Map(),
      settings: {
        frequency: 'daily',
        timeRange: { start: '09:00', end: '18:00' },
        minPriority: 'medium',
        enableSound: true,
        enableDesktop: true
      },
      unreadCount: 0
    }
  },
  mounted() {
    this.initializeNotificationCenter()
    this.loadSettings()
    this.setupIntelligentAgentListeners()
  },
  beforeUnmount() {
    this.cleanupTimers()
    this.removeIntelligentAgentListeners()
  },
  methods: {
    // 初始化通知中心
    initializeNotificationCenter() {
      console.log('🔔 通知中心已启动')
      
      // 请求通知权限
      if ('Notification' in window && Notification.permission === 'default') {
        Notification.requestPermission()
      }
      
      // 加载历史通知
      this.loadNotificationHistory()
      
      // 模拟一些初始通知
      this.addWelcomeNotifications()
    },
    
    // 设置智能代理监听器
    setupIntelligentAgentListeners() {
      // 监听推送通知
      intelligentAgent.addEventListener('newNotification', (data) => {
        this.handleIncomingNotification(data)
      })
      
      // 监听数字人播报请求
      intelligentAgent.addEventListener('digitalHumanAnnouncement', (data) => {
        this.$emit('digital-human-announce', data)
      })
      
      // 监听推送策略更新
      intelligentAgent.addEventListener('pushStrategyUpdated', (data) => {
        console.log('📊 推送策略已更新:', data)
      })
    },
    
    // 移除智能代理监听器
    removeIntelligentAgentListeners() {
      // 在实际应用中需要移除监听器
    },
    
    // 处理传入的通知
    handleIncomingNotification(data) {
      const notification = {
        id: Date.now() + Math.random(),
        ...data,
        timestamp: new Date(),
        progress: 100,
        isExpanded: false,
        isRead: false
      }
      
      this.addNotification(notification)
    },
    
    // 添加通知
    addNotification(notification) {
      // 确保通知对象包含所有必要的响应式属性
      const completeNotification = {
        ...notification,
        progress: 100,
        isExpanded: notification.isExpanded || false,
        isRead: notification.isRead || false
      }
      
      // 添加到通知列表
      this.notifications.unshift(completeNotification)
      this.visibleNotifications.unshift(completeNotification)
      
      // 更新未读数量
      if (!completeNotification.isRead) {
        this.unreadCount++
      }
      
      // 限制可见通知数量
      if (this.visibleNotifications.length > 5) {
        const removed = this.visibleNotifications.pop()
        this.moveToHistory(removed)
      }
      
      // 设置自动关闭
      this.setAutoClose(completeNotification)
      
      // 播放声音
      if (this.settings.enableSound) {
        this.playNotificationSound(completeNotification.urgency)
      }
      
      // 显示桌面通知
      if (this.settings.enableDesktop && completeNotification.urgency === 'high') {
        this.showDesktopNotification(completeNotification)
      }
    },
    
    // 设置自动关闭
    setAutoClose(notification) {
      const duration = this.getAutoCloseDuration(notification.urgency)
      
      const timer = setTimeout(() => {
        this.dismissNotification(notification.id)
      }, duration)
      
      this.autoCloseTimers.set(notification.id, {
        timer,
        startTime: Date.now(),
        duration,
        remaining: duration
      })
      
      // 开始进度条动画
      this.animateProgress(notification)
    },
    
    // 获取自动关闭时长
    getAutoCloseDuration(urgency) {
      const durations = {
        high: 10000, // 10秒
        medium: 7000, // 7秒
        low: 5000 // 5秒
      }
      return durations[urgency] || 7000
    },
    
    // 动画进度条
    animateProgress(notification) {
      const timerInfo = this.autoCloseTimers.get(notification.id)
      if (!timerInfo) return
      
      const updateProgress = () => {
        const elapsed = Date.now() - timerInfo.startTime
        const progress = Math.max(0, 100 - (elapsed / timerInfo.duration) * 100)
        
        const notificationIndex = this.visibleNotifications.findIndex(n => n.id === notification.id)
        if (notificationIndex !== -1) {
          this.visibleNotifications[notificationIndex].progress = progress
        }
        
        if (progress > 0 && this.autoCloseTimers.has(notification.id)) {
          requestAnimationFrame(updateProgress)
        }
      }
      
      updateProgress()
    },
    
    // 暂停自动关闭
    pauseAutoClose(notification) {
      const timerInfo = this.autoCloseTimers.get(notification.id)
      if (timerInfo) {
        clearTimeout(timerInfo.timer)
        timerInfo.remaining = timerInfo.duration - (Date.now() - timerInfo.startTime)
      }
    },
    
    // 恢复自动关闭
    resumeAutoClose(notification) {
      const timerInfo = this.autoCloseTimers.get(notification.id)
      if (timerInfo && timerInfo.remaining > 0) {
        timerInfo.startTime = Date.now()
        timerInfo.timer = setTimeout(() => {
          this.dismissNotification(notification.id)
        }, timerInfo.remaining)
        
        this.animateProgress(notification)
      }
    },
    
    // 关闭通知
    dismissNotification(id) {
      const index = this.visibleNotifications.findIndex(n => n.id === id)
      if (index !== -1) {
        const notification = this.visibleNotifications[index]
        this.moveToHistory(notification)
        this.visibleNotifications.splice(index, 1)
      }
      
      // 清理定时器
      if (this.autoCloseTimers.has(id)) {
        clearTimeout(this.autoCloseTimers.get(id).timer)
        this.autoCloseTimers.delete(id)
      }
    },
    
    // 展开通知
    expandNotification(notification) {
      notification.isExpanded = !notification.isExpanded
      notification.isRead = true
      if (this.unreadCount > 0) {
        this.unreadCount--
      }
    },
    
    // 移动到历史记录
    moveToHistory(notification) {
      if (!this.notificationHistory.find(n => n.id === notification.id)) {
        this.notificationHistory.unshift(notification)
        
        // 限制历史记录数量
        if (this.notificationHistory.length > 50) {
          this.notificationHistory = this.notificationHistory.slice(0, 50)
        }
        
        this.saveNotificationHistory()
      }
    },
    
    // 获取通知样式
    getNotificationStyle(urgency) {
      const styles = {
        high: 'bg-red-900/80 border-red-500/50 backdrop-blur-sm',
        medium: 'bg-yellow-900/80 border-yellow-500/50 backdrop-blur-sm',
        low: 'bg-blue-900/80 border-blue-500/50 backdrop-blur-sm',
        normal: 'bg-gray-900/80 border-electric-500/50 backdrop-blur-sm'
      }
      return styles[urgency] || styles.normal
    },
    
    // 获取通知图标
    getNotificationIcon(type) {
      const icons = {
        policy_update: FileText,
        market_change: TrendingUp,
        risk_alert: AlertTriangle,
        opportunity: Target,
        daily_digest: Bell,
        welcome: Info,
        reanalysis: Building
      }
      return icons[type] || Bell
    },
    
    // 获取图标颜色
    getIconColor(urgency) {
      const colors = {
        high: 'text-red-400',
        medium: 'text-yellow-400',
        low: 'text-blue-400',
        normal: 'text-electric-500'
      }
      return colors[urgency] || colors.normal
    },
    
    // 查看政策详情
    viewPolicyDetails(notification) {
      this.$emit('view-policy-details', notification.data)
    },
    
    // 播放通知声音
    playNotificationSound(urgency) {
      // 简单的音频反馈
      const audioContext = new (window.AudioContext || window.webkitAudioContext)()
      const frequency = urgency === 'high' ? 800 : urgency === 'medium' ? 600 : 400
      
      const oscillator = audioContext.createOscillator()
      const gainNode = audioContext.createGain()
      
      oscillator.connect(gainNode)
      gainNode.connect(audioContext.destination)
      
      oscillator.frequency.setValueAtTime(frequency, audioContext.currentTime)
      oscillator.type = 'sine'
      
      gainNode.gain.setValueAtTime(0.1, audioContext.currentTime)
      gainNode.gain.exponentialRampToValueAtTime(0.01, audioContext.currentTime + 0.3)
      
      oscillator.start(audioContext.currentTime)
      oscillator.stop(audioContext.currentTime + 0.3)
    },
    
    // 显示桌面通知
    showDesktopNotification(notification) {
      if ('Notification' in window && Notification.permission === 'granted') {
        new Notification(notification.title, {
          body: notification.content,
          icon: '/digital-human-avatar.webp'
        })
      }
    },
    
    // 添加欢迎通知
    addWelcomeNotifications() {
      setTimeout(() => {
        this.addNotification({
          id: 'welcome-1',
          type: 'welcome',
          title: '智能助手已启动',
          content: '欢迎使用智能政策助手！我将为您提供个性化的政策推荐和及时提醒。',
          urgency: 'normal',
          timestamp: new Date(),
          isRead: false
        })
      }, 1000)
    },
    
    // 加载设置
    loadSettings() {
      const saved = localStorage.getItem('notification_settings')
      if (saved) {
        this.settings = { ...this.settings, ...JSON.parse(saved) }
      }
    },
    
    // 保存设置
    saveSettings() {
      localStorage.setItem('notification_settings', JSON.stringify(this.settings))
      
      // 更新智能代理配置
      intelligentAgent.agentConfig.pushPreferences = {
        ...intelligentAgent.agentConfig.pushPreferences,
        frequency: this.settings.frequency,
        timeRange: this.settings.timeRange,
        priority: this.settings.minPriority
      }
      
      this.showSettings = false
    },
    
    // 加载通知历史
    loadNotificationHistory() {
      const saved = localStorage.getItem('notification_history')
      if (saved) {
        this.notificationHistory = JSON.parse(saved)
      }
    },
    
    // 保存通知历史
    saveNotificationHistory() {
      localStorage.setItem('notification_history', JSON.stringify(this.notificationHistory))
    },
    
    // 清理定时器
    cleanupTimers() {
      this.autoCloseTimers.forEach(timerInfo => {
        clearTimeout(timerInfo.timer)
      })
      this.autoCloseTimers.clear()
    },
    
    // 格式化时间
    formatTime(timestamp) {
      return new Date(timestamp).toLocaleTimeString('zh-CN', {
        hour: '2-digit',
        minute: '2-digit'
      })
    },
    
    // 格式化日期
    formatDate(date) {
      if (!date) return ''
      return new Date(date).toLocaleDateString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit'
      })
    }
  }
}
</script>

<style scoped>
.notification-slide-enter-active,
.notification-slide-leave-active {
  transition: all 0.5s ease;
}

.notification-slide-enter-from {
  opacity: 0;
  transform: translateX(100%);
}

.notification-slide-leave-to {
  opacity: 0;
  transform: translateX(100%);
}

.notification-card {
  backdrop-filter: blur(10px);
  cursor: pointer;
}

.notification-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 10px 25px rgba(0, 0, 0, 0.3);
}
</style> 